<template>
  <el-card>

    <div class="department-management">
      <!-- 操作栏 -->
      <div class="toolbar">
        <!--      <el-input v-model="searchKeyword" placeholder="请输入部门名称" size="small" style="width: 200px; margin-right: 10px;" />
              <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>-->
        <el-button type="success" size="small" @click="openAddDialog" style="margin-left: 10px;">新增班级</el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="dataList" stripe border style="width: 100%; margin-top: 20px;">
        <el-table-column v-if="false" prop="id" label="部门ID" width="80" />
        <el-table-column prop="name" label="班级名称" />
        <el-table-column prop="majorid" label="所属专业" />
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 新增/编辑对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
        <el-form :model="form" label-width="100px">
          <el-form-item label="班级名称">
            <el-input
                v-model="form.name"
                size="small"
                style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="所属专业">
            <el-select
                v-model="form.majorid"
                size="small"
                style="width: 100%"
            >
              <el-option
                  v-for="(classification, index) in chooseTagmajorList"
                  :key="index"
                  :label="classification.name"
                  :value="classification.id"
              />
              <el-option :label="$t('m.Unclassified')" :value="null" />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </el-card>

</template>

<script>
import api from '@/common/api';

export default {
  data() {
    return {
      chooseTagmajorList: [],
      searchKeyword: '',
      departments: [],
      dialogVisible: false,
      dialogTitle: '新增班级',
      form: {
        id: null,
        name: '',
        depid: '',
      },
      dataList:[]
    };
  },
  computed: {
    filteredDepartments() {
      const keyword = this.searchKeyword.trim();
      if (!keyword) return this.departments;
      return this.departments.filter(d => d.name.includes(keyword));
    }
  },
  methods: {
    getTagClassification(){
      api.register_getTagmajorlist().then((res)=>{
        this.chooseTagmajorList = res.data.data;
        this.chooseTagmajorList = this.chooseTagmajorList.filter(c=>c.oj == this.tag.oj);
      })
    },
    handleSearch() {
      // 搜索逻辑由 computed 属性处理
    },
    openAddDialog() {
      this.dialogTitle = '新增班级';
      this.form = { id: null, depname: ''};
      this.dialogVisible = true;
    },
    openEditDialog(row) {
      this.dialogTitle = '编辑班级';
      this.form = { ...row };
      this.dialogVisible = true;
    },
    /*    handleSubmit() {
          if (this.form.id) {
            // 修改逻辑
            const index = this.departments.findIndex(d => d.id === this.form.id);
            if (index !== -1) {
              this.departments.splice(index, 1, { ...this.form });
            }
          } else {
            // 新增逻辑
            const newId = this.departments.length
                ? Math.max(...this.departments.map(d => d.id)) + 1
                : 1;
            this.departments.push({ ...this.form, id: newId });
          }
          this.dialogVisible = false;
        },*/

    async handleSubmit() {
      try {
        if (this.form.id) {
          // 更新逻辑
          const res = await api.admin_updateclazz(this.form);
          if (res.status === 200) {  // 假设成功返回code为200
            const index = this.departments.findIndex(d => d.id === this.form.id);
            if (index !== -1) {
              this.departments.splice(index, 1, { ...this.form });
            }
            this.loading = true;
            this.getList()
            this.$message.success('更新成功');
          } else {
            this.$message.error(res.msg || '更新失败');
          }
        } else {
          // 新增逻辑
          const res = await api.admin_addclazz(this.form);
          if (res.status === 200) {
            // 使用后端返回的ID（推荐）
            /*            const newDep = { ...this.form, id: res.data.id };
                        this.departments.push(newDep);*/
            this.loading = true;
            this.getList()
            this.$message.success('新增成功');
          } else {
            this.$message.error(res.msg || '新增失败');
          }
        }
        this.dialogVisible = false;
        // 可选：重置表单
        this.form = { id: null, name: '' };
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error('请求失败，请检查网络');
      }
    },
    handleDelete(rowData) {
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 传递整行数据到后台
        api.admin_deleteclazz(rowData)
            .then(res => {
              if (res.status === 200) {
                this.dataList = this.dataList.filter(d => d.id !== rowData.id);
                this.$message.success(res.msg || '删除成功');
                this.getList();
              } else {
                this.$message.error(res.msg || '删除失败');
              }
            })
      }).catch(() => {
        // 用户点击取消
      });
    },
    async getList(){
      const res =   await api.admin_getClazzList()
      console.log(res,'res')
      this.dataList = res.data.data
    }
  },
  created() {
    this.getList()
    this.getTagClassification()
  }
};
</script>

<style scoped>
.department-management {
  padding: 20px;
}
.toolbar {
  display: flex;
  align-items: center;
}
</style>
